package com.guandi.geekbrowser.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.POJONode;
import com.guandi.geekbrowser.Utils.DESHelper;
import com.guandi.geekbrowser.Utils.EasyUtil;
import com.guandi.geekbrowser.primary.entity.Message;
import com.guandi.geekbrowser.primary.entity.Role;
import com.guandi.geekbrowser.primary.entity.Tab;
import com.guandi.geekbrowser.primary.entity.User;
import com.guandi.geekbrowser.primary.service.DetailsService;
import com.guandi.geekbrowser.primary.service.RoleService;
import com.guandi.geekbrowser.primary.service.TabService;
import com.guandi.geekbrowser.primary.service.UserService;
import com.guandi.geekbrowser.secondary.entity.ForumUser;
import com.guandi.geekbrowser.secondary.service.ForumUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Controller
public class HomeController {

    @Autowired
    private DetailsService detailsService;
    @Autowired
    private UserService userService;
    @Autowired
    private TabService tabService;
    @Autowired
    private ForumUserService forumUserService;
    @Autowired
    private RoleService roleService;

    private DESHelper desHelper = new DESHelper("zDsGrVKQ");

    @RequestMapping(value = "/")
    @ResponseBody
    public String hello() {
        return "hello world!";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String login(@RequestBody JSONObject jsonObject) throws Exception {
        String user = (String) jsonObject.get("user");
        String password = (String) jsonObject.get("password");
        String activeCode = (String) jsonObject.get("activeCode");
        String machineCode = (String) jsonObject.get("machineCode");
        User curUser = userService.findByNameAndPassword(user, password);
        Message message = new Message();
        if (curUser != null) {
            message = checkUser(message, activeCode, curUser, curUser, machineCode);
        } else {
            ForumUser forumUser = forumUserService.findByUsername(user);
            if (forumUser != null) {
                String newPassword = EasyUtil.md5(EasyUtil.md5(password) + forumUser.getSalt());
                ForumUser newUser = forumUserService.findByUsernameAndPassword(user, newPassword);
                if (newUser != null) {
                    User userTemp = userService.findByNameAndPassword(forumUser.getUsername(), password);
                    if (userTemp == null) {
                        User userForum = new User();
                        String id = UUID.randomUUID().toString().replaceAll("-", "");
                        userForum.setId(id);
                        userForum.setName(forumUser.getUsername());
                        userForum.setPassword(password);
                        userService.saveUser(userForum);
                        Role role = new Role();
                        role.setUserId(userForum.getId());
                        role.setName("ordinary");
                        roleService.save(role);
                        message = checkUser(message, activeCode, userForum, userForum, machineCode);
                    } else {
                        message = checkUser(message, activeCode, userTemp, userTemp, machineCode);
                    }
                } else {
                    message.setMessage("账号或密码错误!");
                    message.setSuccess(false);
                }
            } else {
                message.setMessage("账号不存在!");
                message.setSuccess(false);
            }
        }
        return JSONObject.toJSONString(message);
    }

    private Message checkUser(Message message, String activeCode, User userForum, User curUser, String machineCode) {
        int limitUser = 3; //限制用户机器登录数量
        String valActiveCode = userForum.getValActiveCode() == null ? "" : curUser.getValActiveCode();
        String activeCodeDB = userForum.getActiveCode() == null ? "" : curUser.getActiveCode();
        if (!EasyUtil.isEmpty(activeCode) || !EasyUtil.isEmpty(activeCodeDB)) {
            if (activeCodeDB.equals(activeCode) || !EasyUtil.isEmpty(valActiveCode)) {
                if (activeCodeDB.equals(activeCode)) {
                    curUser.setValActiveCode(activeCode);
                    userService.saveUser(curUser);
                }
                //保存用户机器码
                String machineCodeNotSave = curUser.getMachineCode();
                if (EasyUtil.isEmpty(machineCodeNotSave) && !EasyUtil.isEmpty(machineCode)) {
                    curUser.setMachineCode(machineCode);
                    userService.saveUser(curUser);
                } else if (!EasyUtil.isEmpty(machineCodeNotSave) && !EasyUtil.isEmpty(machineCode)) {
                    String[] split = machineCodeNotSave.split(",");
                    if (split.length < limitUser && !machineCodeNotSave.contains(machineCode)) {
                        String concat = machineCodeNotSave.concat("," + machineCode);
                        curUser.setMachineCode(concat);
                        userService.saveUser(curUser);
                    }
                }
                //判断机器码是否存在及是否存在上限
                String machineCodeSave = curUser.getMachineCode();
                if (!EasyUtil.isEmpty(machineCodeSave)) {
                    String[] split = machineCodeSave.split(",");
                    if(split.length<=3) {
                        if (machineCodeSave.contains(machineCode) ||
                                curUser.getName().equals("aaaa") ||
                                curUser.getName().equals("zjjxcv") ||
                                curUser.getName().equals("gd")) {
                            message.setMessage("成功");
                            String uidStr = desHelper.encrypt(curUser.getId());
                            message.setParams(uidStr);
                            message.setSuccess(true);
                            List<Tab> tabList = tabService.findByUserIdAndDel(curUser.getId(), false);
                            if (tabList != null & tabList.size() > 0) {
                                Tab tab = tabList.get(0);
                                message.setTabName(tab.getName());
                            } else {
                                message.setTabName("");
                            }
                        } else {
                            message.setMessage("当前账号已在其他机器授权登录!");
                            message.setSuccess(false);
                        }
                    }else{
                        message.setMessage("登录授权超过上限!");
                        message.setSuccess(false);
                    }
                } else {
                    message.setMessage("未授权!");
                    message.setSuccess(false);
                }
            } else {
                message.setMessage("激活码不存在!");
                message.setSuccess(false);
            }
        } else {
            message.setMessage("请输入激活码!");
            message.setSuccess(false);
        }
        return message;
    }

    @RequestMapping(value = "/getUser", method = RequestMethod.POST)
    @ResponseBody
    public String getUser(@RequestBody JSONObject jsonObject) {
        String userId = (String) jsonObject.get("userId");
        if (!EasyUtil.isEmpty(userId)) {
            userId = desHelper.decrypt(userId);
            Optional<User> user = userService.findById(userId);
            if (user.isPresent()) {
                return user.get().getName();
            }
        }
        return "";
    }

    @RequestMapping(value = "/getRoles", method = RequestMethod.POST)
    @ResponseBody
    public String getRoles(@RequestBody JSONObject jsonObject) {
        String userId = (String) jsonObject.get("userId");
        if (!EasyUtil.isEmpty(userId)) {
            userId = desHelper.decrypt(userId);
            Role role = roleService.findByUserId(userId);
            if (role != null) {
                return role.getName();
            }
        }
        return "";
    }

    @RequestMapping(value = "/generateCode", method = RequestMethod.POST)
    @ResponseBody
    public String generateCode(@RequestBody JSONObject jsonObject) throws Exception {
        String forumUser = jsonObject.getString("forumUser");
        String userId = jsonObject.getString("userId");
        Message message = new Message();
        if (!EasyUtil.isEmpty(forumUser)&&!EasyUtil.isEmpty(userId)) {
            userId = desHelper.decrypt(userId);
            User user = userService.findByName(forumUser.trim());
            Role role = roleService.findByUserId(userId);
            if (user != null&&role.getName().equals("admin")) {
                if (EasyUtil.isEmpty(user.getActiveCode())) {
                    String en = desHelper.encrypt(user.getName() + "@beisushequ@");
                    String md5 = EasyUtil.md5(en);
                    user.setActiveCode(md5);
                    userService.saveUser(user);
                    message.setSuccess(true);
                    message.setMessage("成功!");
                    message.setParams(md5);
                } else {
                    message.setSuccess(true);
                    message.setMessage("成功!");
                    message.setParams(user.getActiveCode());
                }
            } else {
                message.setSuccess(false);
                message.setMessage("用户未登陆!");
            }
        } else {
            message.setSuccess(false);
            message.setMessage("用户不能为空!");
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/getUserList", method = RequestMethod.POST)
    @ResponseBody
    public String getUserList(@RequestBody JSONObject jsonObject){
        String userId = jsonObject.getString("userId");
        String searchWord = jsonObject.getString("searchWord");
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer pageNumber = jsonObject.getInteger("pageNumber");
        if(!EasyUtil.isEmpty(userId)){
            userId = desHelper.decrypt(userId);
            Role role = roleService.findByUserId(userId);
            if (role.getName().equals("admin")) {
                Page<User> page = userService.findAllByAdmin(searchWord, pageSize, pageNumber);
                page.getContent().stream().forEach(f->{
                    Role roleTemp = roleService.findByUserId(f.getId());
                    f.setRoleName(roleTemp.getName());
                });
                return JSONObject.toJSONString(page);
            }
        }
        return "";
    }

    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ResponseBody
    public String updateUser(@RequestBody JSONObject jsonObject){
        String userId = jsonObject.getString("userId");
        String editMachineCode = jsonObject.getString("editMachineCode");
        String editValActiveCode = jsonObject.getString("editValActiveCode");
        String editRoleName = jsonObject.getString("editRoleName");
        String editId = jsonObject.getString("editId");
        Message message = new Message();
        if(!EasyUtil.isEmpty(userId)&&editId!=null){
            userId = desHelper.decrypt(userId);
            Role role = roleService.findByUserId(userId);
            if (role.getName().equals("admin")) {
                Optional<User> userOptional = userService.findById(editId);
                if (userOptional.isPresent()&&!EasyUtil.isEmpty(editRoleName)) {
                    User user = userOptional.get();
                    user.setMachineCode(editMachineCode);
                    user.setValActiveCode(editValActiveCode);
                    userService.saveUser(user);
                    Role roleTemp = roleService.findByUserId(editId);
                    roleTemp.setName(editRoleName);
                    roleService.save(roleTemp);
                    message.setSuccess(true);
                    message.setMessage("修改成功!");
                }else{
                    message.setSuccess(false);
                    message.setMessage("账号不存在!");
                }
            }else{
                message.setSuccess(false);
                message.setMessage("没有权限操作!");
            }
        }else{
            message.setSuccess(false);
            message.setMessage("参数异常!");
        }
        return JSONObject.toJSONString(message);
    }

}
